package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxTradeOrderList;
import com.adk.backend.service.TradeOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 贸易订单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/trade-order")
public class TradeOrderController {
    
    @Autowired
    private TradeOrderService tradeOrderService;
    
    /**
     * 分页查询贸易订单列表
     */
    @RequiresPermission("list")
    @GetMapping("/list")
    public Result<PageResult<Map<String, Object>>> getTradeOrderList(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Integer orderType,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) Integer ywId,
            @RequestParam(required = false) Integer customerId,
            @RequestParam(required = false) Integer cid,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String orderDate,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer isRecvCustomInfo,
            @RequestParam(required = false) Integer isChecking,
            @RequestParam(required = false) Integer declearStatus,
            @RequestParam(required = false) Integer financeStatus,
            @RequestParam(required = false) Integer ib,
            @RequestParam(required = false) Integer aId,
            @RequestParam(required = false) String ata,
            @RequestParam(required = false) String shipperBl,
            @RequestParam(required = false) String awb,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            HttpServletRequest request) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("orderType", orderType);
        params.put("shipType", shipType);
        params.put("ywId", ywId);
        // 优先使用 cid，如果没有则使用 customerId
        if (cid != null && cid > 0) {
            params.put("customerId", cid);
        } else {
            params.put("customerId", customerId);
        }
        params.put("status", status);
        params.put("orderDate", orderDate);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("isRecvCustomInfo", isRecvCustomInfo);
        params.put("isChecking", isChecking);
        params.put("declearStatus", declearStatus);
        params.put("financeStatus", financeStatus);
        // is_booking 参数：PHP中 ib>0 时，查询条件是 is_booking=(ib-1)
        if (ib != null && ib > 0) {
            params.put("isBooking", ib - 1);
        }
        // add_uid 参数：PHP中是 a_id
        if (aId != null && aId > 0) {
            params.put("addUid", aId);
        }
        params.put("ata", ata);
        params.put("shipperBl", shipperBl);
        params.put("awb", awb);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        // 处理用户权限：如果用户组是4，则只查询自己的订单
        Integer userGroup = (Integer) request.getAttribute("userGroup");
        Long userId = (Long) request.getAttribute("userId");
        if (userGroup != null && userGroup == 4 && userId != null) {
            params.put("ywId", userId);
        }
        
        PageResult<Map<String, Object>> result = tradeOrderService.getTradeOrderList(params);
        return Result.success(result);
    }
    
    /**
     * 根据ID查询贸易订单详情
     */
    @RequiresPermission("view")
    @GetMapping("/detail")
    public Result<LxTradeOrderList> getTradeOrderDetail(@RequestParam Long id) {
        LxTradeOrderList tradeOrder = tradeOrderService.getTradeOrderById(id);
        if (tradeOrder != null) {
            return Result.success(tradeOrder);
        }
        return Result.error("贸易订单不存在");
    }
    
    /**
     * 根据订单号查询贸易订单
     */
    @RequiresPermission("view")
    @GetMapping("/by-orderno")
    public Result<LxTradeOrderList> getTradeOrderByOrderNo(@RequestParam String orderNo) {
        LxTradeOrderList tradeOrder = tradeOrderService.getTradeOrderByOrderNo(orderNo);
        if (tradeOrder != null) {
            return Result.success(tradeOrder);
        }
        return Result.error("贸易订单不存在");
    }
    
    /**
     * 创建贸易订单
     */
    @RequiresPermission("add")
    @PostMapping("/create")
    public Result<LxTradeOrderList> createTradeOrder(@RequestBody LxTradeOrderList tradeOrder) {
        try {
            // 检查订单号是否已存在
            LxTradeOrderList existing = tradeOrderService.getTradeOrderByOrderNo(tradeOrder.getOrderNo());
            if (existing != null) {
                return Result.error("订单号已存在");
            }
            
            LxTradeOrderList result = tradeOrderService.createTradeOrder(tradeOrder);
            return Result.success("创建成功", result);
        } catch (Exception e) {
            log.error("创建贸易订单失败", e);
            return Result.error("创建贸易订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新贸易订单
     */
    @RequiresPermission("edit")
    @PostMapping("/update")
    public Result<Boolean> updateTradeOrder(@RequestBody LxTradeOrderList tradeOrder) {
        try {
            boolean success = tradeOrderService.updateTradeOrder(tradeOrder);
            if (success) {
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新贸易订单失败", e);
            return Result.error("更新贸易订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除贸易订单
     */
    @RequiresPermission("del")
    @PostMapping("/delete")
    public Result<Boolean> deleteTradeOrder(@RequestParam Long id) {
        try {
            boolean success = tradeOrderService.deleteTradeOrder(id);
            if (success) {
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除贸易订单失败", e);
            return Result.error("删除贸易订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新贸易订单状态
     */
    @RequiresPermission("edit")
    @PostMapping("/update-status")
    public Result<Boolean> updateTradeOrderStatus(@RequestParam Long id, @RequestParam Integer status) {
        try {
            boolean success = tradeOrderService.updateTradeOrderStatus(id, status);
            if (success) {
                return Result.success("更新状态成功", true);
            }
            return Result.error("更新状态失败");
        } catch (Exception e) {
            log.error("更新贸易订单状态失败", e);
            return Result.error("更新贸易订单状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取贸易订单跟踪信息
     */
    @RequiresPermission("view")
    @GetMapping("/tracking")
    public Result<java.util.List<Map<String, Object>>> getTradeOrderTracking(@RequestParam Long orderId) {
        java.util.List<Map<String, Object>> result = tradeOrderService.getTradeOrderTracking(orderId);
        return Result.success(result);
    }
    
    /**
     * 获取贸易订单状态列表
     */
    @RequiresPermission("view")
    @GetMapping("/status-list")
    public Result<Map<String, Object>> getTradeOrderStatusList(@RequestParam Long id) {
        Map<String, Object> result = tradeOrderService.getTradeOrderStatusList(id);
        return Result.success(result);
    }
    
    /**
     * 获取报关检查订单信息
     */
    @RequiresPermission("view")
    @GetMapping("/declear-check")
    public Result<Map<String, Object>> getTradeOrderForDeclearCheck(@RequestParam Long id) {
        Map<String, Object> result = tradeOrderService.getTradeOrderForDeclearCheck(id);
        return Result.success(result);
    }
    
    /**
     * 更新报关检查状态
     */
    @RequiresPermission("edit")
    @PostMapping("/declear-check/save")
    public Result<Boolean> updateDeclearCheck(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            
            boolean success = tradeOrderService.updateDeclearCheck(id, params, userId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新报关检查状态失败", e);
            return Result.error("更新报关检查状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取巴彦订单信息
     */
    @RequiresPermission("view")
    @GetMapping("/bayan")
    public Result<LxTradeOrderList> getTradeOrderForBayan(@RequestParam Long id) {
        LxTradeOrderList tradeOrder = tradeOrderService.getTradeOrderById(id);
        return Result.success(tradeOrder);
    }
    
    /**
     * 更新巴彦信息
     */
    @RequiresPermission("edit")
    @PostMapping("/bayan/save")
    public Result<Boolean> updateBayan(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            
            boolean success = tradeOrderService.updateBayan(id, params, userId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新巴彦信息失败", e);
            return Result.error("更新巴彦信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取贸易费用信息
     */
    @RequiresPermission("view")
    @GetMapping("/trade-fee")
    public Result<Map<String, Object>> getTradeFee(@RequestParam Long id) {
        Map<String, Object> result = tradeOrderService.getTradeFee(id);
        return Result.success(result);
    }
    
    /**
     * 保存贸易费用
     */
    @RequiresPermission("edit")
    @PostMapping("/trade-fee/save")
    public Result<Boolean> saveTradeFee(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            
            boolean success = tradeOrderService.saveTradeFee(id, params, userId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("保存失败");
            }
        } catch (Exception e) {
            log.error("保存贸易费用失败", e);
            return Result.error("保存贸易费用失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传报关文件
     */
    @RequiresPermission("edit")
    @PostMapping("/upload-custom")
    public Result<Boolean> uploadCustom(
            @RequestParam Long id,
            @RequestParam("files") org.springframework.web.multipart.MultipartFile[] files,
            HttpServletRequest request) {
        try {
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            
            boolean success = tradeOrderService.uploadCustom(id, files, userId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("上传失败");
            }
        } catch (Exception e) {
            log.error("上传报关文件失败", e);
            return Result.error("上传报关文件失败：" + e.getMessage());
        }
    }
}

